'use strict'

import { app, BrowserWindow, ipcMain, Menu } from 'electron'

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
const winURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080`
  : `file://${__dirname}/index.html`

function createWindow() {
  /**
   * Initial window options
   */
  Menu.setApplicationMenu(null) // 关闭菜单栏
  mainWindow = new BrowserWindow({
    height: 640,
    width: 960,
    minHeight: 640,
    minWidth: 860,
    frame: false,
    resizable: true,
    useContentSize: true,
    webPreferences: {
      webSecurity: false
    }
  })
  mainWindow.webContents.closeDevTools() // 关闭控制台

  mainWindow.webContents.on('crashed', () => {
    app.quit()
  })

  mainWindow.loadURL(winURL)

  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})

ipcMain.on('min', () => mainWindow.minimize())

ipcMain.on('max', () => {
  if (mainWindow.isMaximized()) {
    mainWindow.unmaximize()
  } else {
    mainWindow.maximize()
  }
})

ipcMain.on('close', () => mainWindow.close())

let settingChildWindow

ipcMain.on('openSettingWindow', () => {
  settingChildWindow = new BrowserWindow({
    height: 475,
    width: 550,
    minHeight: 475,
    minWidth: 550,
    frame: false,
    resizable: false,
    useContentSize: true,
    webPreferences: {
      webSecurity: false
    }
  })
  settingChildWindow.webContents.closeDevTools() // 关闭控制台
  settingChildWindow.loadURL(winURL + '#/setting')
  settingChildWindow.on('closed', () => {
    settingChildWindow = null
  })
})

ipcMain.on('closeSettingWindow', () => {
  settingChildWindow.close()
})
